<!DOCTYPE html>
<html lang="en">
  <head>
    <title>insertAdjacentElement() demo</title>
    <style>
      div {
        width: 50px;
        height: 50px;
        margin: 3px;
        border: 3px solid black;
        display: inline-block;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <p>
      Click colored box to select it, then use the first two buttons below to
      insert elements before and after your selection.
    </p>

    <section>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </section>

    <button class="before">Insert before</button>
    <button class="after">Insert after</button>
    <button class="reset">Reset demo</button>

    <script>
      const beforeBtn = document.querySelector(".before");
      const afterBtn = document.querySelector(".after");
      const resetBtn = document.querySelector(".reset");

      const container = document.querySelector("section");

      let activeElem;

      resetBtn.addEventListener("click", () => {
        while (container.firstChild) {
          container.removeChild(container.firstChild);
        }

        for (let i = 0; i <= 3; i++) {
          let tempDiv = document.createElement("div");
          container.appendChild(tempDiv);
          setListener(tempDiv);
        }
      });

      beforeBtn.addEventListener("click", function () {
        let tempDiv = document.createElement("div");
        tempDiv.style.backgroundColor = randomColor();
        if (activeElem) {
          activeElem.insertAdjacentElement("beforebegin", tempDiv);
        }
        setListener(tempDiv);
      });

      afterBtn.addEventListener("click", function () {
        let tempDiv = document.createElement("div");
        tempDiv.style.backgroundColor = randomColor();
        if (activeElem) {
          activeElem.insertAdjacentElement("afterend", tempDiv);
        }
        setListener(tempDiv);
      });

      function setListener(elem) {
        elem.addEventListener("click", function () {
          const allElems = document.querySelectorAll("section div");
          for (let i = 0; i < allElems.length; i++) {
            allElems[i].style.border = "3px solid black";
          }
          elem.style.border = "3px solid aqua";
          activeElem = elem;
        });
      }

      function randomColor() {
        function random() {
          const result = Math.floor(Math.random() * 255);
          return result;
        }

        return "rgb(" + random() + "," + random() + "," + random() + ")";
      }

      function init() {
        const initElems = document.querySelectorAll("section div");
        for (let i = 0; i < initElems.length; i++) {
          setListener(initElems[i]);
        }
      }

      init();
    </script>
  </body>
</html>
